package com.lookup.api.handler.api;

import java.util.Date;
import java.util.Map;

import org.apache.commons.lang3.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.collect.Maps;
import com.google.inject.Inject;
import com.lookup.api.dto.UserVo;
import com.lookup.api.mapper.BBroadbandUserMapper;
import com.lookup.api.po.BBroadbandUser;
import com.lookup.api.service.LogicService;

import io.vertx.core.json.JsonObject;
import io.vertx.rxjava.ext.web.RoutingContext;

public class ApiHandler {

	private static final Logger log = LoggerFactory.getLogger(ApiHandler.class);
	@Inject
	private LogicService logicService;
	@Inject
	private BBroadbandUserMapper userMapper;

	public void handlePost(RoutingContext ctx) {
		// 从上下文获取请求参数，类似于从httprequest中获取parameter一样
		String param1 = ctx.request().getParam("param1");
		String param2 = ctx.request().getParam("param2");

		UserVo userVo = ctx.getBodyAsJson().mapTo(UserVo.class);
		log.info("req: {}", userVo);

		if ("xxx".equals(param1)) {
			// 如果参数空，交由httpserver提供默认的400错误界面
			ctx.response().setStatusCode(400).end();
			return;
		}

		BBroadbandUser userPO = userMapper.queryByKey("zgx", 201);
		log.info("query user:{}", userPO);

		BBroadbandUser po = new BBroadbandUser();
		po.setUsername(RandomStringUtils.randomAlphanumeric(5).toLowerCase());
		po.setServicetype(Integer.parseInt(RandomStringUtils.randomNumeric(3)));
		po.setStatus(1);
		po.setModdate(new Date());
		int num = userMapper.add(po);
		log.info("add user:{},num:{}", po.getUsername(), num);

		// 申明response类型为json格式，结束response并且输出json字符串
		// ctx.response().putHeader("content-type",
		// "application/json").end(obj.encodePrettily());
		ctx.json(userPO);
	}

	public void handleGet(RoutingContext context) {
		String param1 = context.request().getParam("param1");
		String param2 = context.request().getParam("param2");

		if (isBlank(param1) || isBlank(param2)) {
			context.response().setStatusCode(400).end();
		}
		int num = logicService.getNum();
		log.info("handleGet logicService getNum: {}", num);

		JsonObject obj = new JsonObject();
		obj.put("method", "get").put("param1", param1).put("param2", param2);
		
		Map<String, Object> map=Maps.newHashMap();
		map.put("method", "get");
		map.put("param1", param1);
		map.put("param2", param2);

//		context.response().putHeader("content-type", "application/json").end(obj.encodePrettily());
		context.json(map);
	}

	private static boolean isBlank(String str) {
		if (str == null || "".equals(str))
			return true;
		return false;
	}

}
